#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <execinfo.h>

/*
 * backtrace和bacetrace_symbols打印出回溯信息
 */
 
#if 0
#include <execinfo.h>

int backtrace(void **buffer, int size);
char **backtrace_symbols(void *const *buffer, int size);
void backtrace_symbols_fd(void *const *buffer, int size, int fd);


#endif

#define BACKTRACE_SIZE 16
 
void ShowStack(void)
{
	int i;
	void *buffer[BACKTRACE_SIZE];
 
	int n = backtrace(buffer, BACKTRACE_SIZE);
	printf("[%s]:[%d] n = %d\n", __func__, __LINE__, n);
	char **symbols = backtrace_symbols(buffer, n);
	if(NULL == symbols){
		perror("backtrace symbols");
		exit(EXIT_FAILURE);
	}
	printf("[%s]:[%d]\n", __func__, __LINE__);
	for (i = 0; i < n; i++) {
		printf("%d: %s\n", i, symbols[i]);
	}
 
	free(symbols);
}
 
void sigsegv_handler(int signo)
{
	if (signo == SIGSEGV) {
		printf("Receive SIGSEGV signal\n");
		printf("-----call stack-----\n");
		ShowStack();
		exit(-1);
	} else {
		printf("this is sig %d", signo);
	}
}
 
int main(int argc, char *argv[])
{
	printf("The code compile date:[%s]:[%s] !!!\n", __DATE__, __TIME__);
	signal(SIGSEGV, sigsegv_handler);
	int i = 0;
	char *p = NULL;
	while(1)
	{
		printf("%s:[%s]:[%d]\n", __DATE__, __func__, __LINE__);
		sleep(1);
		i++;
		if(3 == i){
			*p = 0x55;
		}
	}
	return -1;
}

#if 0
    11a1:	48 8d 3d 4b 02 00 00 	lea    0x24b(%rip),%rdi        # 13f3 <main>
    11a8:	ff 15 32 2e 00 00    	callq  *0x2e32(%rip)        # 3fe0 <__libc_start_main@GLIBC_2.2.5>
    11ae:	f4                   	hlt   

    ....

    1296:	e8 75 fe ff ff       	callq  1110 <backtrace@plt>
    129b:	89 85 64 ff ff ff    	mov    %eax,-0x9c(%rbp)

    ....

    13cb:	e8 99 fe ff ff       	callq  1269 <ShowStack>
    13d0:	bf ff ff ff ff       	mov    $0xffffffff,%edi
    13d5:	e8 86 fd ff ff       	callq  1160 <exit@plt>

    ....

    147d:	48 8b 45 f8          	mov    -0x8(%rbp),%rax
    1481:	c6 00 55             	movb   $0x55,(%rax)         // SIGSEGV

The code compile date:[May  9 2024]:[11:41:58] !!!
May  9 2024:[main]:[63]
May  9 2024:[main]:[63]
May  9 2024:[main]:[63]
Receive SIGSEGV signal
-----call stack-----
[ShowStack]:[29] n = 6
[ShowStack]:[35]
0: ./backtrace(+0x129b) [0x5598dc3c129b]        // backtrace
1: ./backtrace(+0x13d0) [0x5598dc3c13d0]        // exit
2: /lib/x86_64-linux-gnu/libc.so.6(+0x43090) [0x7f7a16bef090]   // syscall
3: ./backtrace(+0x1481) [0x5598dc3c1481]        // SIGSEGV
4: /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf3) [0x7f7a16bd0083]
5: ./backtrace(+0x11ae) [0x5598dc3c11ae]        // main

#endif


